package com.china_goldcard.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.ViewGroup;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * BaseFragmentPagerAdapter
 * 让Fragment成为ViewPager的一页时，
 * FragmentManager会一直保存管理创建好了的Fragment，
 * 即使当前不是显示的这一页，Fragment对象也不会被销毁，
 * 在后台默默等待重新显示。但如果Fragment不再可见时，
 * 它的视图层次会被销毁掉，下次显示时视图会重新创建。
 * 当使用FragmentPagerAdapter时，一定要为它的宿主ViewPager设置一个有效的ID。
 */
public class BaseFragmentPagerAdapter<T extends Fragment> extends FragmentPagerAdapter {

    protected List<T> dataList;

    protected Map<String,T> fragmentMaps = new HashMap<String,T>();

    @Override
    public Fragment getItem(int position) {
        T fragment = fragmentMaps.get(fragmentMapKey(position));
        if (fragment == null){
            fragment = dataList.get (position);
            fragmentMaps.put (fragmentMapKey(position), fragment);
        }
        return fragment;
    }

    @Override
    public int getCount() {
        return dataList.size();
    }

    public BaseFragmentPagerAdapter(FragmentManager fm, List<T> dataList) {
        super(fm);
        this.dataList = dataList;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container,position,object);
        fragmentMaps.remove (fragmentMapKey(position));
    }

    /**
     * 根据index获取对应的fragment
     * @param index
     * @return
     */
    public T getFragmentByIndex(int index){
        return fragmentMaps.get (fragmentMapKey(index));
    }

    /**
     * index生成key
     * @param index
     * @return
     */
    private String fragmentMapKey(int index){
        return "FragmentMapKey" + index;
    }
}
